﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Net;
using twlib;
using Newtonsoft.Json;
using System.IO;

namespace TeamWork_Client
{
    public partial class Form1 : Form
    {
        private RCon remote_console;
        private string server;
        ChatClient cc;
        string nickname;


        public Form1(RCon rcon)
        {
            InitializeComponent();
            remote_console = rcon;
            server = rcon.ssa;
        }

        public Form1(string s)
        {
            InitializeComponent();
            server = s;
            nickname = File.ReadAllLines("nickname.txt")[0];
        }

        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            /*if (remote_console.coder_accepted)
            {
                submitAnUpdateToolStripMenuItem.Enabled = false;
                submitAnUpdateToolStripMenuItem.Text = "Submit An Update...(Coder Only)";
            }*/
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Dictionary<string, string> d = new Dictionary<string, string>();
            d.Add("packet_type", "GetFiles");
            string[] files = HTTPManager.SendMessage((server + ":8080"), null, d).Split(';');
            foreach (var f in files)
            {
                if (f.Trim().Length > 0 || f != null) //Some checks.
                {
                    treeView1.Nodes.Add(f);
                }
            }
            timer1.Start();
            cc = new ChatClient(server, nickname);
            timer2.Start();
            new System.Threading.Thread(cc_check).Start();
        }

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Text.Length > 0) //Make sure we don't send a NULL name.
            {
                string data = HTTPManager.SendMessage((server + ":8080"), "/download " + e.Node.Text, null);
                richTextBox2.Text = data;
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            richTextBox1.SelectionStart = richTextBox1.Text.Length;
            richTextBox1.SelectionLength = 0;
            richTextBox1.ScrollToCaret();
        }

        private void textBox2_KeyDown(object sender, KeyEventArgs e)
        {
            if (textBox2.Text.Length > 0)
            {
                if (e.KeyCode == Keys.Enter)
                {
                    cc.SendMessage(textBox2.Text);
                    textBox2.Text = "";
                }
            }
        }

        StringBuilder str = new StringBuilder();

        private void timer2_Tick(object sender, EventArgs e)
        {
            /*string nl = null;
            System.Threading.ThreadPool.QueueUserWorkItem(delegate { nl = cc.reader.ReadLine() + Environment.NewLine; });
            richTextBox1.Text += nl;*/
            richTextBox1.Text = str.ToString();
        }

        private void cc_check()
        {
            while (true)
            {
                string msg = cc.reader.ReadLine();
                str.AppendLine(msg);
            }
        }

        [DllImport("Kernel32")]
        private static extern void ExitProcess(int uExitCode);

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Application.Exit();
            ExitProcess(0);
        }

        private void viewModificationEntriesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> Headers = new Dictionary<string, string>();
            Headers.Add("packet_type", "CodeReview");
            Headers.Add("file_name", treeView1.SelectedNode.Text);
            string json = HTTPManager.SendMessage((server + ":8080"), null, Headers);
            List<CodeUpdateTemplate> entries = JsonConvert.DeserializeObject<List<CodeUpdateTemplate>>(json);
            new ModDB(treeView1.SelectedNode.Text, entries).ShowDialog();
        }

        private void submitAnUpdateToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("packet_type", "CodeSubmit");
            headers.Add("code_file", treeView1.SelectedNode.Text);
            headers.Add("author", nickname);
            HTTPManager.SendMessage2((server + ":8080"), richTextBox2.Text, headers);
            MessageBox.Show("Code Update Has Been Submitted.", "Code Update", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
            ExitProcess(0);
        }

    }
}
